import re
from rest_framework import serializers
from .models import Car, Cargo, Location


class LocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ['id', 'city', 'state', 'zipcode', 'latitude', 'longitude']


class LocationZipSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ['zipcode']


class CargoGetSerializer(serializers.ModelSerializer):

    pick_up_location = LocationSerializer(read_only=True, )
    deliver_location = LocationSerializer(read_only=True, )
    count_car = serializers.IntegerField(read_only=True)

    class Meta:
        model = Cargo
        fields = ['id', 'cargo_weight', 'pick_up_location', 'deliver_location', 'count_car']


class CargoCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Cargo
        fields = ['pick_up_location',  'deliver_location', 'cargo_weight', 'description']


class CargoCarSerializer(serializers.ModelSerializer):
    distance = serializers.FloatField()
    current_location = LocationSerializer()

    class Meta:
        model = Car
        fields = ['id', 'unique_car_number', 'current_location', 'payload_type', 'distance']


class CargoGetIdSerializer(serializers.ModelSerializer):

    pick_up_location = LocationSerializer(read_only=True)
    deliver_location = LocationSerializer(read_only=True)
    cars = CargoCarSerializer(read_only=True, many=True)

    class Meta:
        model = Cargo
        fields = ['id', 'cargo_weight', 'description', 'pick_up_location', 'deliver_location', 'cars']


class CargoPatchSerializer(serializers.ModelSerializer):

    class Meta:
        model = Cargo
        fields = ['cargo_weight', 'description']


class CarIdSerializer(serializers.ModelSerializer):
    current_location = LocationSerializer(read_only=True)

    class Meta:
        model = Car
        fields = ['id', 'unique_car_number', 'payload_type', 'current_location', ]


class CarPatchSerializer(serializers.ModelSerializer):
    current_location = serializers.SlugRelatedField(slug_field='zipcode',
                                                    queryset=Location.objects.all(),
                                                    write_only=True,)
    current_location_details = LocationZipSerializer(source='current_location', read_only=True)

    class Meta:
        model = Car
        fields = ['unique_car_number', 'payload_type', 'current_location', 'current_location_details']


class CarSerializer(serializers.ModelSerializer):
    current_location = LocationSerializer(read_only=True)

    class Meta:
        model = Car
        fields = ['id', 'unique_car_number', 'payload_type',  'current_location']
